﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace WebBrowserTest.Analyzers
{
    public class GooglePositionAnalyzer
    {
        private HtmlDocument _htmlDoc = new HtmlDocument();
        public int GetGooglePosition(string html, string url)
        {
            
            _htmlDoc.LoadHtml(html);
            var links = _htmlDoc.DocumentNode.SelectNodes("//a[@class='l']");
            int pos = 0;
            int result = 0;
            if(links!=null)
            {
                var hrefAttr = links.Select(o => o.Attributes["href"] == null ? "" : o.Attributes["href"].Value);
            
                foreach (var attr in hrefAttr)
                {
                    pos++;
                    string hrefVal = attr;
                    if(attr[attr.Length - 1] == '/')
                    {
                        hrefVal = attr.Substring(0, attr.Length - 1);
                    }
                    if (url[url.Length - 1] == '/')
                    {
                        url = url.Substring(0, url.Length - 1);
                    }
                    if (hrefVal == url)
                    {
                        result = pos;
                        break;
                    }
                }
            }
            return result;
        }
    }
}
